<template>
  <div class="viewport">
    <div class="main_content">
      <column-left :chartData="chartData"/>
      <column-center :chartData="chartData"/>
      <column-right :chartData="chartData"/>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { getMenuList, userCount } from '@/api/index'
export default {
  data () {
    return {
      // 建立的连接
      ws: null,
      // 是否真正建立连接
      lockReconnect: false,
      // 30秒一次心跳
      timeout: 28 * 1000,
      // 心跳心跳倒计时
      timeoutObj: null,
      // 心跳倒计时
      serverTimeoutObj: null,
      // 断开 重连倒计时
      timeoutnum: null,
      chartData: {},
      isClose: true,
      timer: null
    }
  },
  components: {
    'Header': () => import('./components/header'),
    'ColumnLeft': () => import('./components/columnLeft'),
    'ColumnCenter': () => import('./components/columnCenter'),
    'ColumnRight': () => import('./components/columnRight')
  },
  created () {
    this.isClose = true
    let themeName = localStorage.getItem('themeName')
    document.body.className = themeName !== null ? themeName : 'theme-light'
    // if (this.ws) {
    //   this.onclose()
    // }
    this.initWebpack()
    this.getMenu()
    this.userCount()
    // this.timer = setInterval(this.userCount, 5000)
  },
  beforeDestroy  () {
    this.isClose = false
    // // this.cloes()
    // this.ws.onclose = this.close
    // clearInterval(this.timer)
    // this.onclose()
    this.ws.close()
    // this.cloes()
  },
  destroyed () {
    this.isClose = false
    // this.ws.onclose = this.close
    // this.onclose()
    this.ws.close()
    // this.ws.onclose = this.close
    // clearInterval(this.timer)
  },
  methods: {
    async userCount () {
      const data = await userCount()
      if (data) {
        if (data.code === 200) {
          sessionStorage.setItem('userCount', data.data)
        }
      }
    },
    // 获取菜单
    async getMenu () {
      const data = await getMenuList()
      if (data) {
        if (data.code === 200) {
          this.$store.commit('setPerms', data.data)
        }
      }
    },
    initWebpack () {
      if (typeof WebSocket === 'undefined') {
        alert('您的浏览器不支持WebSocket')
        return false
      }
      let url = 'ws:' + window.SITE_CONFIG.websocketUrl + '/websocket'
      this.ws = new WebSocket(url)
      this.ws.onopen = this.onopen
      this.ws.onmessage = this.onmessage
      this.ws.onclose = this.onclose
      this.ws.onerror = this.onerror
    },
    // 重新连接
    reconnect () {
      let that = this
      if (that.lockReconnect) {
        return
      }
      that.lockReconnect = true
      // 没连接上会一直重连，设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum)
      that.timeoutnum = setTimeout(function () {
        // 新连接
        that.initWebpack()
        that.lockReconnect = false
      }, 5000)
    },
    // 重置心跳
    reset () {
      const that = this
      // 清除时间
      clearTimeout(that.timeoutObj)
      clearTimeout(that.serverTimeoutObj)
      // 重启心跳
      that.start()
    },
    onopen () {
      console.log('open')
      // 开启心跳
      this.start()
    },
    // 开启心跳
    start () {
      if (this.isClose) {
        const self = this
        self.timeoutObj && clearTimeout(self.timeoutObj)
        self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
        self.timeoutObj = setTimeout(function () {
          // 这里发送一个心跳，后端收到后，返回一个心跳消息，
          if (self.ws.readyState === 1) {
            // 如果连接正常
            self.ws.send('ping')
          } else {
            // 否则重连
            self.reconnect()
          }
          self.serverTimeoutObj = setTimeout(function () {
            // 超时关闭
            self.ws.onclose()
          }, self.timeout)
        }, self.timeout)
      }
    },
    onmessage (e) {
      const dataJson = e.data
      if (dataJson === '收到消息，消息内容：heartCheck' || dataJson === 'pong') {
        console.log(dataJson)
      } else {
        if (dataJson) {
          this.chartData = JSON.parse(e.data)
          console.log(JSON.parse(e.data))
          localStorage.setItem('chartData', e.data)
        }
      }
      // 收到服务器信息，心跳重置
      this.reset()
    },
    onclose (e) {
      if (e) {
        console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
      }
      if (this.isClose) {
        this.reconnect()
      }
      // // 重连
      // this.reconnect()
    },
    onerror (e) {
      console.log('出现错误')
      // 重连
      this.reconnect()
    },
    cloes () {
      this.isClose = false
      console.log('socket已经关闭')
      // clearTimeout(this.serverTimeoutObj)
    }
  },
  computed: {
    ...mapState('theme', [
      'themeName'
    ])
  }
}
</script>

<style lang="scss" scoped>
</style>
